package com.yzt.minemodule.wxapi;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.yzt.zhuju.network.entity.goods.WeChatPaySignBean;
import com.yzt.zhuju.utils.EmptyUtils;
import com.yzt.p_base.utils.ToastUtil;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

    private static final String TAG = "WXPay";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        WXAPIFactory.createWXAPI(this, "wx4b6080cc0837f2ec", true)
                .handleIntent(getIntent(), this);
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        if (baseResp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            final Bundle bundle = new Bundle();
            baseResp.toBundle(bundle);
            //获取额外数据
            final String extra = bundle.getString("_wxapi_payresp_extdata");
            Log.e(TAG, baseResp.errCode + baseResp.errStr + extra);
            if (EmptyUtils.isEmpty(extra)) {
                finish();
                return;
            }
            final Gson gson = new Gson();
            WeChatPaySignBean extraBean;
            try {
                extraBean = gson.fromJson(extra, WeChatPaySignBean.class);
            } catch (Exception e) {
                finish();
                return;
            }
            if (extraBean == null) {
                finish();
                return;
            }
            extraBean.setCode(baseResp.errCode);
            if (!extraBean.isSuccess() && !extraBean.isCanceled()) {
                ToastUtil.showMessage(baseResp.errStr);
            }
            //  EventHelper.post("wechat_pay", extraBean);
        }
        finish();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, 0);
    }
}
